package com.demo.log;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.demo.util.CommonContrants;
import com.demo.util.HttpContextUtils;
import com.demo.util.UUIDGenerater;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        LocalDateTime startTime = LocalDateTime.now();
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        String traceId = req.getHeader(CommonContrants.HEADER_TRACE_ID);
        if (traceId == null) {
            traceId = UUIDGenerater.genUUID();
        }
        request.setAttribute(CommonContrants.HEADER_TRACE_ID, traceId);
        String uri = req.getRequestURI();
        String ip = HttpContextUtils.getIpAddr(req);
        request.setAttribute(CommonContrants.HEADER_TRACE_IP, ip);
        log.info("[trace-id:{}] [method:{}] [path:{}] [client-ip:{}]", traceId, req.getMethod(), uri, ip);
        chain.doFilter(request, response);
        log.info("[trace-id:{}] [method:{}] [path:{}]  [cost:{}] [status:{}]", traceId, req.getMethod(), uri,
             Duration.between(startTime, LocalDateTime.now()).toMillis(), res.getStatus());
    }

    

}
